package com.shanghai.market.plshnaghai.utils;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.shanghai.market.plshnaghai.publics.LogCat;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ImageUtils {

	/**
	 * 超，高，中，低清的图片size
	 */
	private static final int SUPER_SIZE = 1600;
	private static final int HIGH_SIZE = 1200;
	private static final int MIDDLE_SIZE = 800;
	private static final int LOW_SIZE = 640;

	/**
	 * 超，高，中，低清图片的质量
	 */
	public static final int SUPER_QUALITY = 4;
	public static final int HIGH_QUALITY = 3;
	public static final int MIDDLE_QUALITY = 2;
	public static final int LOW_QUALITY = 1;

	public static Bitmap getBitmapFromUri(Uri paramUri, int type) throws FileNotFoundException {
		int i = computeMaxSize(type);
		return getBitmapFromFileDescriptor(paramUri, i, i);
	}

	private static Bitmap getBitmapFromFileDescriptor(Uri paramUri, int width, int height)
			throws FileNotFoundException {

		ParcelFileDescriptor parcelFileDescriptor = FileUtils
				.getParcelFileDescriptorFromUri(paramUri);
		FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

		options.inSampleSize = computeSampleSize(options, width, height);
		options.inJustDecodeBounds = false;
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		options.inPurgeable = true;
		options.inInputShareable = true;
		Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);

		try {
			parcelFileDescriptor.close();
			if (bitmap == null)
				throw new FileNotFoundException();
			// bitmap.setHasAlpha(true);
			bitmap = correctRotation(bitmap, FileUtils.getFilePahtFromUri(paramUri), true);
		} catch (IOException localIOException) {
			LogCat.e("get bitmap from FileDescriptor failed!");
		}

		return bitmap;
	}

	private static int computeMaxSize(int type) {
		switch (type) {
		case LOW_QUALITY:
			return LOW_SIZE;
		case MIDDLE_QUALITY:
			return MIDDLE_SIZE;
		case HIGH_QUALITY:
			return HIGH_SIZE;
		default:
			return SUPER_SIZE;
		}
	}

	private static int computeSampleSize(BitmapFactory.Options paramOptions, int width,
			int height) {
		int i = Math.max(1, width);
		int j = Math.max(1, height);
		int k = (int) Math.max(Math.ceil((double) paramOptions.outWidth / i),
				Math.ceil((double) paramOptions.outHeight / j));
		return k;
	}

	/**
	 * 旋转图片到正确的方向
	 *
	 * @param paramBitmap
	 * @param paramString
	 * @param paramBoolean
	 * @return
	 */
	public static Bitmap correctRotation(Bitmap paramBitmap, String paramString,
			boolean paramBoolean) {
		if (paramString == null)
			return paramBitmap;
		try {
			int k = Integer.valueOf(new ExifInterface(paramString).getAttribute("Orientation"))
					.intValue();
			int i;
			switch (k) {
			case 4:
				i = 180;
				break;
			case 5:
				i = 90;
				break;
			case 7:
				i = 90;
				break;
			case 6:
				i = 90;
				break;
			case 3:
				i = 180;
				break;
			case 8:
				i = 270;
				break;
			default:
				i = 0;
				break;
			}
			if (i != 0) {
				Matrix localMatrix = new Matrix();
				localMatrix.postRotate(i);
				Bitmap localBitmap = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(),
						paramBitmap.getHeight(), localMatrix, false);
				if (paramBoolean)
					paramBitmap.recycle();
				return localBitmap;
			}
		} catch (IOException e) {
			LogCat.e("fail to correct rotation image");
		}
		return paramBitmap;
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	public static String getPath(final Context context, final Uri uri) {
		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/" + split[1];
				}

				// TODO handle non-primary volumes
			}

			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				Uri contentUri = null;
				if ("image".equals(type)) {
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection, selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {

			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}

	public static String getDataColumn(Context context, Uri uri, String selection,
			String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
					null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	/**
	 * 低于4.4使用
	 *
	 * @param context
	 * @param data
	 * @return
	 */
	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	public static String getPath(Context context, Intent data) {
		Uri selectedImage = data.getData();
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null,
				null, null);
		cursor.moveToFirst();
		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		String picturePath = cursor.getString(columnIndex);
		cursor.close();
		return picturePath;
	}
}
